package org.jiucheng.magpiebridge.manager.handler;

import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;

import org.jiucheng.ioc.annotation.Inject;
import org.jiucheng.magpiebridge.manager.util.JwtUtil;
import org.jiucheng.magpiebridge.manager.util.ThreadArgs;
import org.jiucheng.web.WebWrapper;
import org.jiucheng.web.handler.DefaultHandler;
import org.jiucheng.web.util.WebUtil;

public class UserCheckHandler extends DefaultHandler {
    @Inject
    private JwtUtil jwtUtil;
    
    @Override
    public boolean before(WebWrapper webWrapper) throws ServletException {
        Cookie[] cookies = WebUtil.getRequest().getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    String token = cookie.getValue();
                    try {
                        Map<String, String> claims = jwtUtil.verifyToken(token);
                        Long gid = Long.parseLong(claims.get("gid"));
                        ThreadArgs.setGid(gid);
                        ThreadArgs.setGemail(claims.get("gemail"));
                        ThreadArgs.setIsSuper(claims.get("isSuper"));
                        return true;
                    } catch (Exception e) {
                        // e.printStackTrace();
                        break;
                    }
                }
            }
        }
        WebUtil.redirect("/login?utm_source=" + webWrapper.getCtrl().getRoute());
        return false;
    }
}
